package cn.initcap.concurrency.concurrency.atomic;

import cn.initcap.concurrency.annoations.ThreadSafe;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author initcap
 * @date Created in 2018/6/13 PM9:34.
 */
@Slf4j
@ThreadSafe
public class AtomicIntegerFieldUpdaterExample {

    private static final int EXPECT = 100;
    private static final int UPDATE = 200;
    /**
     * {@see AtomicIntegerFieldUpdater}是用来更新指定类的某一个字段的值，并且
     * 这个字段必须是通过volatile修饰且不能被static修饰。
     */
    private static final AtomicIntegerFieldUpdater<AtomicIntegerFieldUpdaterExample> UPDATER = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterExample.class, "count");
    private static AtomicIntegerFieldUpdaterExample example5 = new AtomicIntegerFieldUpdaterExample();
    @Getter
    public volatile int count = 100;

    public static void main(String[] args) {

        if (UPDATER.compareAndSet(example5, EXPECT, UPDATE)) {
            log.info("update success 1 ,{}", example5.getCount());
        }

        if (UPDATER.compareAndSet(example5, EXPECT, UPDATE)) {
            log.info("update success 2 ,{}", example5.getCount());
        } else {
            log.info("update failed 2 ,{}", example5.getCount());
        }
    }
}
